//
//  CHMainTabBar.swift
//  Weibo
//
//  Created by charmer on 16/9/20.
//  Copyright © 2016年 charmer. All rights reserved.
//

import UIKit

class CHMainTabBar: UITabBar {
    //加号按钮的闭包属性
    var composeCallback: (() -> Void)?
    
    
//懒加载加号按钮
    lazy var composeButton: UIButton = {
        let button = UIButton()
        //设置背景
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), for: .normal)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_heighlighted"), for: .highlighted)
        //设置图片
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), for: .normal)
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), for: .highlighted)
        //添加点击事件
        button.addTarget(self, action: #selector(composeDidClick), for: .touchUpInside)
        //添加到tabbar
        self.addSubview(button)
        return button
    }()
    //按钮点击事件
    func composeDidClick() -> Void {
    
        //调用闭包
        composeCallback?()
    }
    
    let count = 5
    override func layoutSubviews() {
        super.layoutSubviews()
        
        //宽度
        let width = self.frame.width/CGFloat(count)
        let height = self.frame.height
        
        var index = 0
        for subView in self.subviews {
        //subviews里面还有其他的子控件，判断subView是tabBarButton类型就修改位置
            if subView.isKind(of: NSClassFromString("UITabBarButton")!) {
            
                let x = CGFloat(index) * width
                let y: CGFloat = 0
                let newFrame = CGRect(x: x, y: y, width: width, height: height)
                subView.frame = newFrame
                index += 1
                if index == 2 {
                    composeButton.frame = CGRect(x: CGFloat(index) * width, y: y, width: width, height: height)
                    index = 3
                }
            }
        }
    
        
    }

}
